package com.ys.controller.api.purchase;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.purchase.TcgInvoiceOffset;
import com.ys.entity.purchase.TcgInvoiceOffsetItem;
import com.ys.entity.sys.YsCol;
import com.ys.service.flow.YspTaskService;
import com.ys.service.purchase.TcgInvoiceOffsetService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 * 发票预核销单
 */
@Controller
@RequestMapping("/api/inter/tcgInvoiceOffset")
public class ApiInterTcgInvoiceOffsetController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcgInvoiceOffsetController.class);

    @Autowired
    private CommonApiService<TcgInvoiceOffset> commonApiService;
    @Autowired
    private CommonApiService<TcgInvoiceOffsetItem> commonApiServiceItem;

    @Autowired
    private TcgInvoiceOffsetService tcgInvoiceOffsetService;

    @Autowired
    private YspTaskService yspTaskService;

    //菜单id
    private Long menuId = MenuId.TCG_InvoiceOffset;

    //权限字符
    private final String PERMISSIONS_VIEW = "tcgInvoiceOffset:view";
    private final String PERMISSIONS_ADD = "tcgInvoiceOffset:add";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcgInvoiceOffset setSeachSql(TcgInvoiceOffset cond){

        cond
                .addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间

                .addLeftJoin("TB_CompanyInfo C ON C.Vid = A.CompanyVid ")//公司信息表
                .addField("C.Vname AS vname")//购买方公司名称
                .addField("C.Tax AS tax")//购买方公司税号

                .addLeftJoin("TCW_PartnerBankInfo PBI ON PBI.Id = A.PartnerBankInfoId ")//合作商银行账户管理
                .addField("PBI.PartnerName AS partnerName")//供应方公司名称
                .addField("PBI.Vgssh AS vgssh")//供应方公司税号

                .addLeftJoin("TCG_InvoiceOffsetItem S ON S.Pbid = A.Bid ")//子表
                .addField("S.InvoiceModelNo AS invoiceModelNo")//发票型号
                .addField("S.InvoiceName AS invoiceName")//发票品名
                .addField("S.OffsetNum AS offsetNum")//发票本次核销数量
                .addField("S.OffsetAmount AS offsetAmount")//本次核销金额

                .addLeftJoin("TCG_PurchaseContractItem PCI ON PCI.Id = S.PurchaseContractItemId ")//采购合同管理子表
                .addField("PCI.Pbid AS purchaseContractBid")//采购合同单号
                .addField("PCI.SubBomNumber AS subBomNumber")//子件BOM数量
                .addField("PCI.SubPurchaseNum AS subPurchaseNum")//子件采购数量
                .addField("PCI.SubPurchasePrice AS subPurchasePrice")//子件采购单价
                .addField("PCI.SubWriteOffNum AS subWriteOffNum")//子件已核销数量

                .addLeftJoin("TCG_PurchaseAppointOrderProductComponent PAC ON PAC.Id = PCI.OrderProductComponentId")//预约采购管理子件表
                .addLeftJoin("TCG_PurchaseAppointOrderItem PAOI ON PAOI.Id = PAC.Pid")//预约采购管理母件表
                .addLeftJoin("TCG_PurchaseAppointOrder PPC ON PPC.Bid = PAOI.Pbid")//预约采购单母表
                .addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = PPC.Vgsbm")//运营公司管理表

                .addField("PPC.Bid AS appointOrderBid")//预约采购单单号
                .addField("PPC.Vgsbm AS vgsbm")//运营公司编码
                .addField("OCA.Vgsjc AS vgsjc")//运营公司简称
                .addField("PAOI.ProductCode AS productCode")//商品编码
                .addField("PAOI.ProductName AS productName")//商品名称
                .addField("PAOI.CodeMerge AS codeMerge")//合并商品编码
                .addField("PAC.SubCode AS subCode")//子件编码
                .addField("PAC.SubName AS subName")//子件名称
                .addField("PAC.SubCodeMerge AS subCodeMerge")//子件合并编码


        //排序
        .setOrderby("A.Bid DESC");

        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TcgInvoiceOffset cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 弹出框
     */
    @RequestMapping("/searchModal")
    @ResponseBody
    public LayuiTableVoJA searchModal(@ModelAttribute TcgInvoiceOffsetItem cond){
    	
    	cond.addLeftJoin("TCG_InvoiceOffset AA ON AA.Bid = A.Pbid")
    		.addField("AA.Bid bid");
    	
    	cond.addLeftJoin("TB_CompanyInfo B ON B.Vid = AA.CompanyVid")
    		.addField("B.Vname companyVname")
    		.addField("B.Tax companyTax");
    	
    	cond.addLeftJoin("TCW_PartnerBankInfo C ON C.Id = AA.PartnerBankInfoId")
    		.addField("C.PartnerName partnerName")
    		.addField("C.Vgssh partnerVgssh");
    	
    	cond.addLeftJoin("TCG_PurchaseContractItem BB ON BB.Id = A.PurchaseContractItemId")
    		.addField("BB.SubPurchasePrice subPurchasePrice")
    		.addField("BB.SubPurchaseNum subPurchaseNum")
    		
    		.addLeftJoin("TCG_PurchaseAppointOrderProductComponent CC ON CC.Id = BB.OrderProductComponentId")
    		.addField("CC.SubCode subCode")
    		.addField("CC.SubName subName")
    		
    		.where("A.Id NOT IN (SELECT InvoiceOffsetItemId FROM TCG_InvoiceRegistItem)");
    	
        return commonApiServiceItem.searchLay(cond);
    }


    /**
     * 加载明细(通过bid)
     */
    @RequestMapping("/listItemByBid")
    @ResponseBody
    public R listItemByBid(String bid){
    	if (bid == null || bid.length() == 0) {
			return R.error("单号不能为空");
		}
    	List<Map<String, Object>> listMap = new TcgInvoiceOffsetItem()
    			.setPbid(bid)
    			
    			.addField("A.Id invoiceOffsetItemId")

    			.addLeftJoin("TCG_PurchaseContractItem AA ON AA.Id = A.PurchaseContractItemId")
    			.addField("AA.SubPurchasePrice subPurchasePrice")
    			.addLeftJoin("TCG_PurchaseContract BB ON BB.Bid = AA.Pbid")
    			.addField("BB.Bid bidPurchaseContract")
    			
    			.addLeftJoin("TCG_PurchaseAppointOrderProductComponent CC ON CC.Id = AA.OrderProductComponentId")
    			.addField("CC.SubCode subCode")
    			.addField("CC.SubName subName")
    			.addField("CC.SubCodeMerge subCodeMerge")
    			.addLeftJoin("TCG_PurchaseAppointOrderItem DD ON DD.Id = CC.Pid")
    			.addField("DD.Pbid bidPurchaseAppointOrder")
    			.addField("DD.ProductCode productCode")
    			.addField("DD.ProductName productName")
    			.addField("DD.CodeMerge codeMerge")
    			.addLeftJoin("TCG_PurchaseAppointOrder EE ON EE.Bid = DD.Pbid")
    			.addField("EE.Vgsbm vgsbm")
    			.addLeftJoin("THR_OperateCompanyApply FF ON FF.Vgsbm = EE.Vgsbm")
    			.addField("FF.Vgsjc vgsjc")
    			
    			.queryMap();
        return R.ok(listMap);
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcgInvoiceOffset cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcgInvoiceOffset> util = new ExportExcelUtils<>(new TcgInvoiceOffset());
            String toFilePath = util.exportExcel(listData, listField, "发票预核销单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcgInvoiceOffsetService.add(params,menuId);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcgInvoiceOffsetService.update(params,menuId);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 删除
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tcgInvoiceOffsetService.del(id);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 流转通过
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcgInvoiceOffsetService.flowPass(id,ShiroUtils.getUserId());
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转退回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        try {
            TcgInvoiceOffset entity = new TcgInvoiceOffset().setId(id).queryFirst();
            return yspTaskService.flowRefuse(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            TcgInvoiceOffset entity = new TcgInvoiceOffset().setId(id).queryFirst();
            return yspTaskService.flowInit(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }








}